<?php
/**
 * Created by PhpStorm.
 * User: Weizehua
 * Date: 8/7/2016
 * Time: 19:48
 */
function get_code($path)
{
    $data = file_get_contents($path);
    
    // remove "<?php" prefix
    return substr($data, 5);
}

function stringify_code($str)
{
    return stringify_code_1($str);
}
function stringify_code_2($str)
{
    return var_export($str, 'true');
}
function stringify_code_1($str)
{
    $pattenPass = "#[A-Za-z0-9 '=*-_;>})\\<\\{\\(]#";
    $pattenSlash = "#[\\\$\"\\\\]#";
    $res = "\"";
    $count = strlen($str);
    for ($i = 0; $i < $count; $i++)
    {
        $v = $str[$i];
        if(preg_match($pattenSlash, $v))
        {
            $res .= "\\$v";
        }
        else if (preg_match($pattenPass, $v))
        {
            $res .= $str[$i];
        }
        else
        {
            $hex = bin2hex($v);
            $res .= "\\x$hex";
        }
    }
    return $res . "\"";
}

function to_shellcode($normalCode)
{
    $stringify = stringify_code($normalCode);
    return "eval($stringify);";
}

function preg_replacement_quote($replacement)
{
    $res = "";
    $count = strlen($replacement);
    for ($i = 0; $i < $count; $i++)
    {
        $v = $replacement[$i];
        if ($v == '\\' || $v == "\$")
        {
            $res .= "\\$v";
        }
        else
        {
            $res .= $replacement[$i];
        }
    }
    return $res;
}

function generate_assign_patten($variable_name)
{
//    return "(?<=^\\\$$variable_name = ).*(?=;$)";
//    return "/(?<=^\\\$$variable_name = ).*(?=;( *(//.*|/\\*.*\\*/)?)?$)/";
//    return "#(?<=\\\$$variable_name = ).*(?=;)#";
    return "#(?<=\\\$$variable_name = ).*(?=;(( |/\\*.*\\*/)*(//.*)?)?)#";
}

function generate_server_url($path)
{
    $path_to_document_root = dirname($_SERVER['PHP_SELF']) . "/$path";
    return "http://{$_SERVER['SERVER_NAME']}:{$_SERVER['SERVER_PORT']}$path_to_document_root";
}
